<template>
  <div class="message-pagination">
    <el-card>
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button type="primary" @click.prevent="handleAdd">
          新增消息通知
        </el-button>
      </div>

      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        v-loading="tableLoading"
        border
      >
        <el-table-column prop="categoryName" label="类型" width="120" />
        <el-table-column prop="title" label="标题" width="180" />
        <el-table-column prop="content" label="内容" min-width="300">
          <template #default="scope">
            <div class="table-inner-content">
              <el-tooltip :content="scope.row.content" placement="top">
                <template #content>
                  <div style="width: 500px">{{ scope.row.content }}</div>
                </template>
                {{ scope.row.content }}</el-tooltip
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status == '1' ? 'primary' : 'success'">
              {{ row.status == '1' ? '草稿' : '已发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="success" size="small" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click.prevent="showRemoveDialog(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="70%">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="消息类型">
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入消息类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="消息标题">
          <el-input
            v-model="formData.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="消息内容">
          <div class="editor-wrapper">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="formData.content"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
            style="width: 100%"
            ref="upload"
            class="upload-demo"
            :before-upload="canUpload"
            :http-request="handleUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-remove="handleRemove"
            :fileList="formData.attachments"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传doc/pdf/zip等格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio value="1">草稿</el-radio>
            <el-radio value="2">发布</el-radio>
          </el-radio-group>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
    <NoticeMessageRemove v-model="removeRef"></NoticeMessageRemove>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, onBeforeUnmount, onMounted, reactive } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import OSS from 'ali-oss'
import { ElMessage } from 'element-plus'
import {
  addNoticeMessage,
  updateNoticeMessage,
  getNoticeMessagePagination,
  getNoticeMessageDetail,
  batchRemoveNoticeMessage,
} from '@/api/sys-notice-message.api.ts'
import NoticeMessageRemove from './component/NoticeMessageRemove.vue'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const mode = 'default' // 或 'simple'
const attachList = ref([])
// 表单数据
const formData = ref({
  id: null,
  categoryName: '',
  title: '',
  content: '',
  status: '2',
  attachments: [],
})
// OSS客户端配置
const ossClient = new OSS({
  region: 'oss-cn-shenzhen',
  accessKeyId: 'LTAI5t741H6okseZdRMDhe9U',
  accessKeySecret: 'dz8VyL0oQa6xPIge8kfzPBQbpM1ZKQ',
  bucket: 'yunhaiwuxian',
})

// 编辑器配置
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        try {
          const fileName = `mengze/images/${Date.now()}_${file.name}`
          const res = await ossClient.put(fileName, file)
          console.log('上传内容:', res)
          insertFn(res.url, file.name, res.url)
        } catch (err) {
          console.error('上传失败:', err)
        }
      },
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        try {
          const fileName = `mengze/videos/${Date.now()}_${file.name}`
          const res = await ossClient.put(fileName, file)
          console.log('上传内容:', res)
          insertFn(res.url, file.name)
        } catch (err) {
          console.error('上传失败:', err)
        }
      },
    },
  },
}

const canUpload = async (rawFile) => {
  // let name = rawFile.name
  // let index = name.indexOf('.')
  // let exet = name.substring(index + 1)
  // if (!(exet === 'jpg' || exet === 'png' || exet === 'jpeg')) {
  //   ElMessage({
  //     message: '只能接受 jpg/png 格式的图片文件',
  //     type: 'error',
  //   })
  //   return false
  // }
  return true
}

const handleUpload = async (option) => {
  try {
    let file = option.file
    const fileName = `mengze/attach/${Date.now()}_${file.name}`
    const res = await ossClient.put(fileName, file)
    formData.value.attachments.push({
      name: file.name,
      url: res.url,
      uid: file.uid,
    })
  } catch (err) {
    console.error('上传失败:', err)
  }
}

const handleRemove = (file, fileList) => {
  console.log('被删除文件:', file)
  console.log('剩余文件列表:', fileList)

  let attachments = formData.value.attachments || []
  formData.value.attachments = attachments.filter((item) => {
    let isFilter = false
    if (item.uid && file.uid) {
      isFilter = item.uid == file.uid
    }
    if (item.url && file.url) {
      isFilter = item.url == file.url
    }
    return !isFilter
  })
}

const uploadError = (err, file, fileList) => {
  ElMessage({
    message: err.msg || err,
    type: 'error',
  })
}

const uploadSuccess = (response, file, fileList) => {
  ElMessage({
    message: '附件上传成功',
    type: 'success',
  })
  return
}

// 工具栏配置
const toolbarConfig = {
  excludeKeys: ['group-video', 'insertTable', 'codeBlock'],
}

const tableLoading = ref(false)
const tableData = ref([])

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: '消息通知',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

const getDataList = () => {
  tableLoading.value = true
  getNoticeMessagePagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
      formData.pageIndex = Number(res.pageIndex)
      formData.pageSize = Number(res.pageSize)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}
onMounted(() => {
  getDataList()
})

const dialogVisible = ref(false)
const dialogEditDisable = ref(false)
const dialogTitle = ref('新增消息通知')
const isEdit = ref(false)

// 创建编辑器
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value == null) return
  editorRef.value.destroy()
})

// 新增消息
const handleAdd = () => {
  dialogTitle.value = '新增消息通知'
  isEdit.value = false
  formData.value = {
    id: null,
    categoryName: '',
    title: '',
    content: '',
    status: '1',
    attachments: [],
  }
  dialogVisible.value = true
  dialogEditDisable.value = false
  editorConfig.readonly = false
}

// 编辑消息
const handleEdit = (row) => {
  console.log('row: ', row)
  dialogTitle.value = '消息通知详情'
  isEdit.value = true

  formData.value = JSON.parse(JSON.stringify(row))
  formData.value.status = `${formData.value.status}`
  if (row.attachments) {
    try {
      let attachments = JSON.parse(row.attachments) || []
      formData.value.attachments = attachments
    } catch (e) {
      print('item.attachments parse:', e)
    }
  }

  console.log('formData', formData)
  dialogVisible.value = true
  dialogEditDisable.value = true
  editorConfig.readonly = true
}

// 删除消息
const handleDelete = (id) => {
  messageList.value = messageList.value.filter((item) => item.id !== id)
  ElMessage.success('删除成功')
}

// 上传成功回调
const handleUploadSuccess = (response, file, fileList) => {
  formData.value.attachments = fileList.map((item) => ({
    name: item.name,
    url: item.response?.url || item.url,
  }))
}

// 提交表单
const handleSubmit = () => {
  if (!formData.value.title) {
    ElMessage.warning('请输入标题')
    return
  }

  let attachments = formData.value.attachments || []
  attachments = attachments.map((item) => {
    return {
      url: item.url,
      name: item.name,
    }
  })
  let data = {
    ...formData.value,
  }
  if (attachments) {
    data.attachments = JSON.stringify(attachments)
  }

  console.log('formData:', data)

  //修改
  if (data.id) {
    updateNoticeMessage(data)
      .then((res) => {
        ElMessage({
          message: '消息通知更新成功',
          type: 'success',
        })
        getDataList()
      })
      .catch((err) => {
        ElMessage({
          message: err.msg || err,
          type: 'error',
        })
      })
  } else {
    addNoticeMessage(data)
      .then((res) => {
        ElMessage({
          message: '消息通知新增成功',
          type: 'success',
        })
        getDataList()
      })
      .catch((err) => {
        ElMessage({
          message: err.msg || err,
          type: 'error',
        })
      })
  }

  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.message-container {
  padding: 20px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.editor-wrapper {
  border: 1px solid #ccc;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.table-inner-content {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
